import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../utils/screen_adapter.dart';
import '../utils/route_util.dart';

class WebViewPage extends StatefulWidget {
  final String title;
  final bool centerTitle;
  final bool showOpenInBrowser;
  final String url;
  final String domData;

  WebViewPage({
    @required this.title,
    this.centerTitle = true,
    this.showOpenInBrowser = false,
    this.url,
    this.domData = '<p>请输入有效链接或内容</p>',
  });

  @override
  State<StatefulWidget> createState() {
    return _WebViewPageState();
  }
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController _webViewController;

  _parseDom2Url(String htmlContents) {
    return Uri.dataFromString(
            htmlContents
//              ..replaceAll('<img', '<img style="max-width:100%;height:auto')
            ,
            mimeType: 'text/html',
            encoding: Encoding.getByName('utf-8'))
        .toString();
  }

  _buildDom() {
    return SizedBox(
      height: ScreenAdapter.screenHeightDp,
      child: WebView(
        initialUrl: widget.url ?? '',
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _webViewController = webViewController;
          if (widget.url == null)
            _webViewController.loadUrl(_parseDom2Url(widget.domData));
        },
      ),
    );
  }

  var isLoad = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        elevation: 0.4,
        centerTitle: widget.centerTitle,
        title: new Text(
          widget.title,
          style: TextStyle(fontSize: 34.asSp),
        ),
//        bottom: new PreferredSize(
//          child: SizedBox(
//            height: 2,
//            child: isLoad ? new LinearProgressIndicator() : Container(),
//          ),
//          preferredSize: Size.fromHeight(2),
//        ),
        actions: <Widget>[
          (widget.url != null && widget.showOpenInBrowser)
              ? IconButton(
                  tooltip: '用浏览器打开',
                  icon: Icon(Icons.language, size: 20.0),
                  onPressed: () {
                    RouteUtil.launchInBrowser(widget.url, title: widget.title);
                  },
                )
              : SizedBox.shrink()
        ],
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: _buildDom(),
      ),
    );
  }
}
